package com.hippo.core.core.network.interceptor

import android.util.Log
import com.hippo.core.BuildConfig
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import java.io.IOException
import java.nio.charset.StandardCharsets

/**
 * 日志拦截器
 */
class LoggerInterceptor : Interceptor {



    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "url : " + request.url)
            Log.d(TAG, "method = " + request.method)
            Log.d(TAG, "token = " + request.headers["userToken"])
//            Log.d(TAG, "header = " + request.headers)

            if ("POST" == request.method) {
                val sb = StringBuilder()
                if (request.body is FormBody) {
                    val body = request.body as FormBody?
                    for (i in 0 until body!!.size) {
                        sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",")
                    }
                    sb.delete(sb.length - 1, sb.length)
                    Log.d(TAG, "params:{$sb}")
                } else if (request.body is RequestBody) {
                    val requestBody = request.body
                    val buffer = Buffer()
                    requestBody!!.writeTo(buffer)
                    val params = buffer.readString(UTF8)
                    Log.d(TAG, "params: $params")
                }
            }
            val originalResponse: Response = chain.proceed(request)
            val responseBody = originalResponse.body
            val source = responseBody!!.source()
            source.request(Long.MAX_VALUE) // Buffer the entire body.
            val buffer = source.buffer
            var charset = UTF8
            val contentType = responseBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(UTF8)
            }
            val contentLength = responseBody.contentLength()
            if (contentLength != 0L) {
                val response = buffer.clone().readString(charset!!)
                Log.d(TAG, "Response :$response")
            }
            return originalResponse
        }
        return chain.proceed(request)
    }

    companion object {
        private val UTF8 = StandardCharsets.UTF_8
        private const val TAG = "okhttp"
    }
}